using System.IO;
using System.Linq;
using UnityEngine;

#if UNITY_EDITOR
using UnityEditor;
#endif

namespace ETModel
{

    public static class LoadHelper
    {
        const string CodeABName = "code.unity3d";
        public static TextAsset LoadCode(string name)
        {
            if (Define.IsAsync)
            {
#if UNITY_EDITOR
                string codePath = $"Assets/Bundles/Independent/Code.prefab";//Path.Combine(Application.dataPath, "Bundles","Independent","Code.prefab");
                string[] realPath = null;
                realPath = AssetDatabase.GetAssetPathsFromAssetBundle(CodeABName);
                codePath = realPath.FirstOrDefault();
                GameObject code = AssetDatabase.LoadAssetAtPath<GameObject>(codePath);
                if (code == null)
                {
                    throw new System.Exception("请检查 Code是否存在");
                }
                var testAsset = code.GetComponent<ReferenceCollector>().Get<TextAsset>(name);
                return testAsset;
            }
#endif
            else
            {
                //TODO   直接从AB包中加载 code
                Debug.LogError("尚未完成");
                return null;
            }
        }

        //不写这个 ilrt会生成 AssetDatabase的绑定
        public static string[] GetAssetPathsFromAssetBundle(string abName)
        {
#if UNITY_EDITOR
            return AssetDatabase.GetAssetPathsFromAssetBundle(abName);
#else
            Debug.LogError($"非编辑器环境无法调用");
            return null;
#endif
        }


        public static string[] GetAssetBundleDependencies(string abName)
        {
#if UNITY_EDITOR

            return AssetDatabase.GetAssetBundleDependencies(abName, true);
#else
            Debug.LogError($"非编辑器环境无法调用");
            return null;
#endif
        }

        public static UnityEngine.Object LoadAssetAtPath(string path)
        {
#if UNITY_EDITOR
            return AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(path);
#else
            Debug.LogError($"非编辑器环境无法调用");
            return null;
#endif
        }
    }
}